﻿package com.pandemicode.framework.xml {
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import org.osflash.signals.natives.NativeSignal;
	import org.osflash.signals.Signal;
	
	/**
	* @author Michael Lawrence
	* @version 1.0.0
	*/
	public class XMLLoader {
		private var _xmlFile:String;
		private var _urlLoader:URLLoader;
		private var _document:XML;
		private var _autoLoad:Boolean;
		
		private var _urlLoaderCompleted:NativeSignal;
		private var _xmlLoadCompleted:Signal;
		
		public function get xmlLoadCompleted():Signal { return this._xmlLoadCompleted; }
		
		/**
		 * The xml document that was loaded.
		 */
		public function get document():XML { return this._document; }
		
		/**
		 * Simplifies the loading of an xml file.
		 * @param	xmlFile		The path of the xml file to load.
		 */
		public function XMLLoader(xmlFile:String = null, autoLoad:Boolean = true) {
			this._xmlLoadCompleted = new Signal(XML);
			
			this._xmlFile = xmlFile;
			this._autoLoad = autoLoad;
			
			if (this._autoLoad) this.load();
		}

		private function urlLoaderComplete(e:Event):void {
			this._urlLoaderCompleted.remove(this.urlLoaderComplete);
			
			this._document = XML(this._urlLoader.data);
			this._xmlLoadCompleted.dispatch(this._document);
		}
		
		/**
		 * Loads the xml file specified.
		 * @param	xmlFile		The path of the xml file to load.
		 */
		public function load(xmlFile:String = null):void {
			if (xmlFile != null)
				this._xmlFile = xmlFile;
				
			this._urlLoader = new URLLoader(new URLRequest(this._xmlFile));
			this._urlLoaderCompleted = new NativeSignal(this._urlLoader, Event.COMPLETE, Event);
			this._urlLoaderCompleted.add(this.urlLoaderComplete);
		}
	}
}
